﻿using System;
using System.IO;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Dialect;
using NHibernate.Mapping.ByCode;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;

namespace Citi.Test.Domain.NHibernate
{
    public class SessionFactory
    {
        private Configuration configuration;

        public ISessionFactory CreateSessionFactory()
        {
            var connectionString =
                string.Format(
                    System.Configuration.ConfigurationManager.ConnectionStrings["DatabasePath"].ConnectionString, Path.Combine(HttpContext.Current.Server.MapPath("~").Replace("WebUI", "Domain"), @"Database\Teste.db"));
            var configuration = new Configuration();

            configuration.DataBaseIntegration(c =>
            {
                c.Dialect<SQLiteDialect>();
                c.ConnectionString = connectionString;
                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                c.BatchSize = 1;
            });
            configuration.AddMapping(GetMapping());
            configuration.SetProperty("adonet.batch_size", "1");
            return configuration.BuildSessionFactory();
        }

        private static HbmMapping GetMapping()
        {
            var mapper = new ModelMapper();
            mapper.AddMappings(typeof(EntityBase).Assembly.GetExportedTypes());

            return mapper.CompileMappingForAllExplicitlyAddedEntities();
        }
    }
}